

package com.maoshi.shop.multishop.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.maoshi.shop.bean.enums.OfflineHandleEventType;
import com.maoshi.shop.bean.enums.ProdStatusEnums;
import com.maoshi.shop.bean.enums.ProdType;
import com.maoshi.shop.bean.enums.ShopStatus;
import com.maoshi.shop.bean.event.ProdChangeStatusEvent;
import com.maoshi.shop.bean.model.*;
import com.maoshi.shop.bean.param.OfflineHandleEventAuditParam;
import com.maoshi.shop.bean.param.ProductParam;
import com.maoshi.shop.common.exception.MaoshiShopBindException;
import com.maoshi.shop.common.util.Json;
import com.maoshi.shop.common.util.PageParam;
import com.maoshi.shop.security.multishop.util.SecurityUtils;
import com.maoshi.shop.service.*;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * 商品列表、商品发布controller
 *
 * @author lgh
 */
@Controller
@RequestMapping("/prod/prod")
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private MapperFacade mapperFacade;

    @Autowired
    private SkuService skuService;

    @Autowired
    private BasketService basketService;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private OfflineHandleEventService offlineHandleEventService;

    @Autowired
    private ShopDetailService shopDetailService;
    @Autowired
    private ShopAuditingService shopAuditingService;
    /**
     * 分页获取商品信息
     */
    @GetMapping("/page")
    public ResponseEntity<IPage<Product>> page(ProductParam product, PageParam<Product> page) {
        IPage<Product> products = productService.page(page,
                new LambdaQueryWrapper<Product>()
                        .like(StrUtil.isNotBlank(product.getProdName()), Product::getProdName, product.getProdName())
                        .eq(Product::getShopId, SecurityUtils.getShopUser().getShopId())
                        .eq(product.getStatus() != null, Product::getStatus, product.getStatus())
                        .eq(product.getShopCategoryId() != null, Product::getShopCategoryId, product.getShopCategoryId())
                        .like(StrUtil.isNotBlank(product.getProdName()), Product::getProdName, product.getProdName())
                        .ne(Product::getStatus, -1)
                        .orderByDesc(Product::getPutawayTime));
        return ResponseEntity.ok(products);
    }

    /**
     * 分页获取上架的商品信息
     */
    @GetMapping("/pageOnLineProd")
    public ResponseEntity<IPage<Product>> pageOnLineProd(ProductParam product, PageParam<Product> page) {
        IPage<Product> products = productService.page(page,
                new LambdaQueryWrapper<Product>()
                        .eq(Product::getShopId, SecurityUtils.getShopUser().getShopId())
                        .eq(Product::getStatus, 1)
                        .orderByDesc(Product::getPutawayTime));
        return ResponseEntity.ok(products);
    }

    /**
     * 获取信息
     */
    @GetMapping("/info/{prodId}")
    public ResponseEntity<Product> info(@PathVariable("prodId") Long prodId) {
        Product prod = productService.getProductByProdId(prodId);
        if (!Objects.equals(prod.getShopId(), SecurityUtils.getShopUser().getShopId())) {
            throw new MaoshiShopBindException("没有权限获取该商品规格信息");
        }
        List<Sku> skuList = skuService.listByProdId(prodId);
        prod.setSkuList(skuList);

        return ResponseEntity.ok(prod);
    }

    /**
     * 保存
     */
    @PostMapping
    public ResponseEntity<String> save(@Valid @RequestBody ProductParam productParam) {
        checkParam(productParam);
        Long shopId = SecurityUtils.getShopUser().getShopId();
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopId);
        if (Objects.equals(shopDetail.getShopStatus(), ShopStatus.OFFLINE.value())) {
            throw new MaoshiShopBindException("店铺违规下线中，不能发布商品，请联系管理员后重试");
        }
        Product product = mapperFacade.map(productParam, Product.class);
        product.setStatus(1);
        product.setDeliveryMode(Json.toJsonString(productParam.getDeliveryModeVo()));
        product.setShopId(shopId);
        product.setUpdateTime(new Date());
        product.setPutawayTime(new Date());
        product.setCreateTime(new Date());
        product.setVersion(0);
        // 商品销量设置为0
        product.setSoldNum(0);
//        product.setGroupActivityId(0L);
//        product.setSeckillActivityId(0L);
        product.setProdType(ProdType.PROD_TYPE_NORMAL.value());
        product.setActivityId(0L);
        productService.saveProduct(product);
        if(shopId==1){
            System.out.println("官方商店发布产品");
            gftj(product);
        }
        return ResponseEntity.ok().build();
    }
    /**
     * 官方发布
     */
    public void gftj(Product product){
        List<ShopAuditing> list = shopAuditingService.list();
        for(int i= 0;i<list.size();i++){
            if(list.get(i).getShopId()!=1){
                for(int j=0;j<product.getSkuList().size();j++){
                    product.getSkuList().get(i).setStocks(0);
                }
                product.setSuperiorProdId(product.getProdId());
                product.setShopId(list.get(i).getShopId());
                productService.saveProduct(product);
            }
        }
    }

    /**
     * 修改
     */
    @PutMapping
    public ResponseEntity<String> update(@Valid @RequestBody ProductParam productParam) {
        checkParam(productParam);
        Product dbProduct = productService.getProductByProdId(productParam.getProdId());
        if (!Objects.equals(dbProduct.getShopId(), SecurityUtils.getShopUser().getShopId())) {
            return ResponseEntity.badRequest().body("无法修改非本店铺商品信息");
        }
        Long shopId = SecurityUtils.getShopUser().getShopId();
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopId);
        if (Objects.equals(shopDetail.getShopStatus(), ShopStatus.OFFLINE.value())) {
            throw new MaoshiShopBindException("店铺违规下线中，不能修改商品，请联系管理员后重试");
        }

        List<Sku> dbSkus = skuService.listByProdId(dbProduct.getProdId());


        Product product = mapperFacade.map(productParam, Product.class);
        product.setDeliveryMode(Json.toJsonString(productParam.getDeliveryModeVo()));
        product.setUpdateTime(new Date());

        dbProduct.setSkuList(dbSkus);
        productService.updateProduct(product, dbProduct);


        List<String> userIds = basketService.listUserIdByProdId(product.getProdId());

        for (String userId : userIds) {
            basketService.removeShopCartItemsCacheByUserId(userId);
        }
        for (Sku sku : dbSkus) {
            skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId());
        }
        return ResponseEntity.ok().build();
    }

    /**
     * 删除
     */
    @DeleteMapping("/{prodId}")
    public ResponseEntity<Void> delete(@PathVariable("prodId") Long prodId) {
        Product dbProduct = productService.getProductByProdId(prodId);
        if (!Objects.equals(dbProduct.getShopId(), SecurityUtils.getShopUser().getShopId())) {
            throw new MaoshiShopBindException("无法获取非本店铺商品信息");
        }
        List<Sku> dbSkus = skuService.listByProdId(dbProduct.getProdId());
        // 删除商品
        productService.removeProductByProdId(prodId);

        for (Sku sku : dbSkus) {
            skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId());
        }

        List<String> userIds = basketService.listUserIdByProdId(prodId);

        for (String userId : userIds) {
            basketService.removeShopCartItemsCacheByUserId(userId);
        }

        return ResponseEntity.ok().build();
    }


    /**
     * 更新商品状态
     */
    @PutMapping("/prodStatus")
    public ResponseEntity<Void> shopStatus(@RequestBody ProductParam productParam) {
        Long prodId = productParam.getProdId();
        Integer prodStatus = productParam.getStatus();
        Product dbProduct = productService.getProductByProdId(prodId);
        if (!Objects.equals(dbProduct.getShopId(), SecurityUtils.getShopUser().getShopId())) {
            throw new MaoshiShopBindException("无法获取非本店铺商品信息");
        }
        if (!(Objects.equals(dbProduct.getStatus(), ProdStatusEnums.NORMAL.getValue())
                || Objects.equals(dbProduct.getStatus(), ProdStatusEnums.SHOP_OFFLINE.getValue()))) {
            throw new MaoshiShopBindException("商品不在正常状态，修改失败");
        }
        Long shopId = SecurityUtils.getShopUser().getShopId();
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopId);
        if (Objects.equals(shopDetail.getShopStatus(), ShopStatus.OFFLINE.value())) {
            throw new MaoshiShopBindException("店铺处于违规下线中，不能修改商品，请联系管理员后重试");
        }

        Product product = new Product();
        product.setProdId(prodId);
        product.setStatus(prodStatus);
        if (prodStatus == 1) {
            product.setPutawayTime(new Date());
        }
        dbProduct.setStatus(prodStatus);
        // 商品状态改变时的发送事件，让活动下线
        applicationContext.publishEvent(new ProdChangeStatusEvent(dbProduct, dbProduct.getStatus()));

        productService.updateById(product);
        productService.removeProductCacheByProdId(prodId);
        List<String> userIds = basketService.listUserIdByProdId(prodId);

        for (String userId : userIds) {
            basketService.removeShopCartItemsCacheByUserId(userId);
        }
        return ResponseEntity.ok().build();
    }

    /**
     * 违规商品提交审核
     */
    @PostMapping("/auditApply")
    public ResponseEntity<Void> auditApply(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        Product product = productService.getProductByProdId(offlineHandleEventAuditParam.getHandleId());
        if (product == null) {
            throw new MaoshiShopBindException("商品信息不存在");
        }
        productService.auditApply(offlineHandleEventAuditParam.getEventId(), offlineHandleEventAuditParam.getHandleId(), offlineHandleEventAuditParam.getReapplyReason());
        // 移除缓存
        productService.removeProductCacheByProdId(product.getProdId());
        return ResponseEntity.ok().build();
    }

    /**
     * 通过prodId获取最新下线商品的事件
     */
    @GetMapping("/getOfflineHandleEventByProdId/{prodId}")
    public ResponseEntity<OfflineHandleEvent> getByProdId(@PathVariable Long prodId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.PROD.getValue(), prodId);
        return ResponseEntity.ok(offlineHandleEvent);
    }

    private void checkParam(ProductParam productParam) {

        Product.DeliveryModeVO deliveryMode = productParam.getDeliveryModeVo();
        boolean hasDeliverMode = deliveryMode != null
                && (deliveryMode.getHasShopDelivery() || deliveryMode.getHasUserPickUp());
        if (!hasDeliverMode) {
            throw new MaoshiShopBindException("请选择配送方式");
        }
        List<Sku> skuList = productParam.getSkuList();
        boolean isAllUnUse = true;
        for (Sku sku : skuList) {
            if (sku.getStatus() == 1) {
                isAllUnUse = false;
            }
        }
        if (isAllUnUse) {
            throw new MaoshiShopBindException("至少要启用一种商品规格");
        }
    }
}
